package com.hengpeng.itfints.controller.member;

import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.constants.SystemConfigConstants;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.en.ActivityType;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.activity.InviteSendRedPacketRequest;
import com.hengpeng.itfinbase.message.activity.RegisterSendRedPacketRequest;
import com.hengpeng.itfinbase.message.activity.UnfreeRedPacketRequest;
import com.hengpeng.itfinbase.message.userInfo.UserInfoRegisterRequest;
import com.hengpeng.itfinbase.message.userInfo.UserInfoResponse;
import com.hengpeng.itfinbase.message.userInfo.UserLoginRequest;
import com.hengpeng.itfinbase.persist.Partner;
import com.hengpeng.itfinbase.persist.Partner.PartnerType;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfinbase.persist.UserInfo.RegisterSource;
import com.hengpeng.itfinbase.persist.UserInfo.UserInfoType;
import com.hengpeng.itfinbase.persist.VerifyCode.VerifyType;
import com.hengpeng.itfints.config.ConfigUtil;
import com.hengpeng.itfints.config.Configuration;
import com.hengpeng.itfints.constants.SystemConfigUtil;
import com.hengpeng.itfints.constants.TSConstants;
import com.hengpeng.itfints.controller.BaseController;
import com.hengpeng.itfints.tools.CommonUtil;
import com.hengpeng.itfints.tools.PatternUtils;
import com.hengpeng.itfints.vo.MemberSession;

@Controller
public class RegisterController extends BaseController {

    /**
     * <pre>
     * 注册
     * </pre>
     * 
     * @param request
     * @param username
     * @param password
     * @param mobile
     * @param recommendCode
     * @param resp
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/register")
    @ResponseBody
    public ServiceResult<String> register(HttpServletRequest request,
            String username, String password, String mobile,
            String recommendCode, String mobilecode, HttpServletResponse resp,
            String checkcode) throws Exception {
        String isCan = ConfigUtil.getParameter("permissions.regedit");
        if (isCan.equalsIgnoreCase("false")) {
            return validateFailure(ConfigUtil
                    .getParameter("permissions.regedit.disabled.des"));
        }
        if (checkcode == null || checkcode.equals("")) {
            return validateFailure("请输入图片验证码");
        }
        String vcode = (String) request.getSession().getAttribute("vcode");
        String wanneng = Configuration.getValue("itfints.validate.code");

        boolean isValidate = false;
        if (wanneng == null) {
            isValidate = checkcode.equals(vcode);
        } else {
            isValidate = checkcode.equals(vcode) || wanneng.equals(checkcode);
        }
        if (!isValidate) {
            return validateFailure("验证码错误");
        }

        int pleng = password.length();

        if (pleng < 6 || pleng > 16) {
            return validateFailure("密码字符长度应为6-16之间");
        }
        if (mobile == null) {
            return validateFailure("手机号码不能为空");
        } else {
            if (!PatternUtils.MOBILE_PATTERN.matcher(mobile).matches()) {
                return validateFailure("手机号码格式不正确");
            }
        }
        UserInfo user = serviceFactory.getUserService().getUserByMobile(mobile);
        if (user != null) {
            return validateFailure("手机号码已经存在");
        }
        if (StringUtils.isEmpty(mobilecode)) {
            return validateFailure("短信验证码不能为空");
        }

        UserInfoRegisterRequest registerDto = new UserInfoRegisterRequest();
        registerDto.setVerifyCode(mobilecode);
        registerDto.setMobile(mobile);
        registerDto.setPassword(password);
        registerDto.setUsername(mobile);
        registerDto.setUserIpAddress(request.getRemoteAddr());
        registerDto.setType(UserInfoType.PERSON);
        registerDto.setRegisterSource(RegisterSource.WEB);
        registerDto.setRecommendCode(recommendCode);
        registerDto
                .setTransType(TransCodeConstants.MemberTransCode.MEMBER_REGISTER);
        UserInfoResponse response = (UserInfoResponse) serviceFactory
                .getProtFactory().remoteTrans(registerDto);
        ServiceResult<String> sr = getServiceResult(response, null);
        if (!sr.getIsSuccess()) {
            request.getSession().removeAttribute("vcode");
            return sr;
        }
        
        /**
         * 注册成功调用活动接口
         */
        RegisterSendRedPacketRequest registerSendRedPacketRequest = new RegisterSendRedPacketRequest();
        registerSendRedPacketRequest.setUserId(response.getUserInfo().getId());
        registerSendRedPacketRequest.setActivityType(ActivityType.REGISTER_REDPACKET);
        registerSendRedPacketRequest.setTransType(TransCodeConstants.ActivityTransCode.REGISTER_SEND_REDPACKET);
        serviceFactory.getPortActiveFactory().remoteTrans(registerSendRedPacketRequest);
        
        /**
         * 推荐码不为空则，注册成功调用邀请送红包活动接口
         */
        if (!StringHelper.isEmpty(recommendCode)) {
            InviteSendRedPacketRequest inviteSendRedPacketRequest = new InviteSendRedPacketRequest();
            inviteSendRedPacketRequest.setTransType(TransCodeConstants.ActivityTransCode.INVITE_SEND_REDPACKET);
            inviteSendRedPacketRequest.setUserId(response.getUserInfo().getId());
            inviteSendRedPacketRequest.setActivityType(ActivityType.INVITE_REDPACKET);
            serviceFactory.getPortActiveFactory().remoteTrans(inviteSendRedPacketRequest);
        }
        
        /**
         * 注册成功查看是否有未激活的红包,如果有则激活
         */
        UnfreeRedPacketRequest unfreeRedPacketRequest = new UnfreeRedPacketRequest();
        unfreeRedPacketRequest.setTransType(TransCodeConstants.ActivityTransCode.UNFREE_REDPACKET);
        unfreeRedPacketRequest.setMobile(mobile);
        unfreeRedPacketRequest.setUserId(response.getUserInfo().getId());
        unfreeRedPacketRequest.setTrustAccountId(response.getUserInfo().getTrustAccountId());
        serviceFactory.getPortActiveFactory().remoteTrans(unfreeRedPacketRequest);

        MemberSession session = new MemberSession();
        session.setUser(response.getUserInfo());
        request.getSession().setAttribute(TSConstants.CLIENT_SESSION_MEMBER,
                session);
        return sr;
    }

    /**
     * 重新发送邮箱激活码
     * 
     * @param map
     * @param request
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/resendEmailActiveCode")
    @ResponseBody
    public ServiceResult<ResponseMessage> resendEmailActiveCode(ModelMap map,
            HttpServletRequest request, String mobile) {
        ServiceResult<ResponseMessage> result = new ServiceResult<ResponseMessage>();
        ResponseMessage response = new ResponseMessage();
        /**
         * 生成激活码
         */
        String activeCode = CommonUtil.getRandom(6);
        UserInfo user = serviceFactory.getUserService().getUserByMobile(mobile);
        user.setActiveCode(activeCode);
        serviceFactory.getPersistService().update(user);
        /***
         * 发送激活邮件
         */
        StringBuffer url = new StringBuffer();
        String domainName = SystemConfigUtil.getConfigValue("domainName");
        if (!StringUtils.isEmpty(domainName)) {
            if (domainName.indexOf("http://") == -1) {
                url.append("http://");
            }
            url.append(domainName);
        } else {
            url.append(request.getScheme());
            url.append("://");
            url.append(request.getServerName());
            url.append(":");
            url.append(request.getServerPort());
            url.append(request.getContextPath());
        }
        url.append("/memberCenter/doValidEmail.htm");
        serviceFactory.getUserService().sendMailForValid(user.getEmail(),
                user.getUserName(), activeCode, url.toString(),
                "/page/register/active_success.jsp",
                "/page/register/active_error.jsp");
        result.setCode(RespCodeConstants.CommonCode.TRANS_SUC);
        result.setMessage(RespCodeConstants.CommonCode.TRANS_SUC_MSG);
        result.setReturnValue(response);
        return result;
    }

    /**
     * <pre>
     * 注册第二步：登录并开通资金托管账户
     * </pre>
     * 
     * @param request
     * @param username
     * @param password
     * @param mobile
     * @param resp
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/step_two_register_active")
    public String step_two_register_active(ModelMap map,
            HttpServletRequest request, HttpServletResponse res, String mobile,
            String password) throws Exception {
        MemberSession session = getSessionMember(request);
        if (session == null) {
            if (mobile != null) {
                UserInfo user = serviceFactory.getUserService()
                        .getUserByMobile(mobile);
                map.put("user", user);
                UserLoginRequest userLoginRequest = new UserLoginRequest();
                userLoginRequest
                        .setTransType(TransCodeConstants.MemberTransCode.MEMBER_LOGIN);
                userLoginRequest.setUsername(mobile);
                userLoginRequest.setPassword(password);
                userLoginRequest.setUserIpAddress(request.getRemoteAddr());
                UserInfoResponse response = (UserInfoResponse) serviceFactory
                        .getProtFactory().remoteTrans(userLoginRequest);
                ServiceResult<UserInfo> sr = getServiceResult(response,
                        UserInfo.class);
                sr.setReturnValue(response.getUserInfo());
                MemberSession member = serviceFactory.getUserService()
                        .refreshSessionUser(
                                response.getUserInfo().getUserName());
                request.getSession().setAttribute(
                        TSConstants.CLIENT_SESSION_MEMBER, member);
                Partner partner = serviceFactory
                        .getPersistService()
                        .get(Partner.class,
                                SystemConfigUtil
                                        .getConfigValue(SystemConfigConstants.PARTNER_ID));
                if (partner != null
                        && !partner.getPartnerType().equals(PartnerType.FUND)) {
                    member.setIsTrust(true);
                }
            } else {
                return "redirect:/page/login/login.jsp";
            }
        }
        return "/page/register/step_two_active.jsp";
    }

    /**
     * 转向激活页面
     * 
     * @param map
     * @param request
     * @param userId
     * @return
     */
    @RequestMapping(value = "/toActive")
    public String toActive(ModelMap map, HttpServletRequest request,
            String userId) {
        UserInfo user = serviceFactory.getPersistService().get(UserInfo.class,
                Long.parseLong(userId));
        map.put("user", user);

        /**
         * 生成激活码
         */
        String activeCode = CommonUtil.getRandom(6);
        user.setActiveCode(activeCode);
        serviceFactory.getPersistService().update(user);
        /***
         * 发送激活邮件
         */
        StringBuffer url = new StringBuffer();
        String domainName = SystemConfigUtil.getConfigValue("domainName");
        if (!StringUtils.isEmpty(domainName)) {
            if (domainName.indexOf("http://") == -1) {
                url.append("http://");
            }
            url.append(domainName);
        } else {
            url.append(request.getScheme());
            url.append("://");
            url.append(request.getServerName());
            url.append(":");
            url.append(request.getServerPort());
            url.append(request.getContextPath());
        }
        url.append("memberCenter/doValidEmail.htm");
        serviceFactory.getUserService().sendMailForValid(user.getEmail(),
                user.getUserName(), activeCode, url.toString(),
                "/page/register/active_success.jsp",
                "/page/register/active_error.jsp");

        return "/page/register/step_two_active.jsp";
    }

    /**
     * <pre>
     * 激活，成功后转让用户类型选择
     * </pre>
     * 
     * @param map
     * @param request
     * @param email_checkcode
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/doActive")
    public String doActive(ModelMap map, HttpServletRequest request,
            String email_checkcode, Long userid) throws Exception {
        UserInfo user = serviceFactory.getPersistService().get(UserInfo.class,
                userid);
        if (!StringHelper.isEmpty(email_checkcode)
                && email_checkcode.equals(user.getActiveCode())) {
            user.setIsEmailCheck(BoolValue.YES);
            user = serviceFactory.getPersistService().update(user);
            map.put("user", user);
            return "/page/register/active_success.jsp";
        } else {// 验证码不正确
            return "/page/register/active_error.jsp";
        }
    }

    /**
     * 重新登陆
     * 
     * @param map
     * @param request
     * @return
     */
    @RequestMapping(value = "/reLogin")
    public String reLogin(ModelMap map, HttpServletRequest request,
            HttpServletResponse response, String userid, String backurl) {

        MemberSession session = getSessionMember(request);
        if (session != null) {
            session.setIsLogin(false);
            UserInfo user = serviceFactory.getUserService().getUserByUserName(
                    session.getUser().getUserName());
            map.put("endTime", new Date());
            map.put("loginTime", user.getLastLoginTime());
        }
        request.getSession().removeAttribute(TSConstants.CLIENT_SESSION_MEMBER);
        /**
         * 添加返回的url
         */
        Cookie cookie = new Cookie("backurl", backurl);
        response.addCookie(cookie);

        return "/page/login/login.jsp";
    }

    /**
     * <pre>
     * 转向选择用户类型
     * </pre>
     * 
     * @param map
     * @param request
     * @param email_checkcode
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/toselectType")
    public String toselectType(ModelMap map, HttpServletRequest request,
            Long userid) throws Exception {
        UserInfo user = serviceFactory.getPersistService().get(UserInfo.class,
                userid);
        map.put("user", user);
        return "/page/register/step_three_selecttype.jsp";
    }

    /**
     * <pre>
     * 选择类型
     * </pre>
     * 
     * @param map
     * @param request
     * @param typeone
     * @param typetwo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/selectType")
    public String selectType(ModelMap map, HttpServletRequest request,
            String typeone, String typetwo, Long userid) throws Exception {
        UserInfo user = serviceFactory.getPersistService().get(UserInfo.class,
                userid);
        if ("ENTERPRISE".equals(typeone)) {// 企业
            map.put("type", "ENTERPRISE");
            map.put("user", user);
            return "/page/register/fill_enterprise.jsp";
        } else if ("PERSON".equals(typeone)) {// 个人
            map.put("type", "PERSON");
            map.put("user", user);
            return "/page/register/fill_person.jsp";
        } else {// 其他金融类机构
            map.put("financedeptType", typetwo);
            return "/page/register/fill_other.jsp";
        }
    }

    /**
     * <pre>
     * 用户信息保存
     * </pre>
     * 
     * @param map
     * @param request
     * @param user
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/registerSave")
    public String registerSave(ModelMap map, HttpServletRequest request,
            UserInfo user) throws Exception {
        user.setUpdateTime(new Date());
        user.setRegisterTime(new Date());
        serviceFactory.getPersistService().update(user);
        return "/index.htm";
    }

    /**
     * 手机验证发送短信
     * 
     * @return
     */
    @RequestMapping(value = "/sendRegValidSMS")
    @ResponseBody
    public ServiceResult<Long> sendValidSMS(HttpServletRequest request,
            String mobile) {
        ServiceResult<Long> result = new ServiceResult<Long>();
        if (StringUtils.isEmpty(mobile)) {
            return validateFailure("参数为空");
        }
        UserInfo user = serviceFactory.getUserService().getUserByMobile(mobile);
        if (user != null) {
            return validateFailure("新手机号码已经存在");
        }
        Object sendTime = request.getSession().getAttribute("REGSMSTIME");
        long timeInterval = 30l;
        long nowTime = Calendar.getInstance().getTimeInMillis();
        if (sendTime == null) {
            request.getSession().setAttribute("REGSMSTIME", nowTime);
        } else {
            long countDown = nowTime - Long.parseLong(String.valueOf(sendTime));
            if (countDown >= 1000 * timeInterval) {
                request.getSession().setAttribute("REGSMSTIME", nowTime);
            } else {
                return validateFailure((timeInterval - countDown / 1000)
                        + "s后，才能再次发送短信验证码");
            }
        }

        ResponseMessage response = serviceFactory.getUserService()
                .sendSMSForValidMobile(null, mobile, null, VerifyType.REGISTER);
        if (response != null) {
            if (RespCodeConstants.CommonCode.TRANS_SUC.equals(response
                    .getRespCode())) {
                result.setIsSuccess(true);
                result.setMessage("已发送验证邮件");
                result.setReturnValue(timeInterval);
            } else {
                return validateFailure(response.getRespDesc());
            }
        } else {
            return validateFailure("发送验证邮件失败");
        }
        return result;
    }
}
